#!/bin/bash
PATH=/sbin:/usr/bin:$PATH

# Required for Stellent viewers
export LD_LIBRARY_PATH=/opt/novell/groupwise/agents/lib

GWPATH=$1
IPADDR=$2
TYPE=$3
GWNAME=$4
PIDPATH=/var/run/gwack/

function error_exit
{
    echo $1 1>&2
    exit 1 
}


function load_gw
{

	if [ ! -d $PIDPATH ]; then
		mkdir -p $PIDPATH
	fi

	if [ $TYPE == "domain" ]; then
		ARGS="$AGENT --home $GWPATH -ip $IPADDR"
	elif [ $TYPE == "po" ]; then
		ARGS="$AGENT --home $GWPATH -ip $IPADDR --noconfig"
	else
		error_exit "Cant determine agent type"
	fi

	startproc -f -t 3 -p $PIDPATH$GWNAME.pid $ARGS >& /dev/null > /dev/null
		if [ $? != 0 ]; then
			error_exit "Agent load failed"
		fi
	
	AGENTPID=`ps -aef | grep $AGENT | grep $IPADDR | grep -v grep | awk ' { print ($2) } '`
	if [ $? == 0 ]; then
		echo $AGENTPID > $PIDPATH$GWNAME.pid
	else
		error_exit "could not create PID"
	fi

    FILE=$PIDPATH$GWNAME.txt
    echo $IPADDR > $FILE


}


function add_secondary_ip
{
	ip address add $IPADDR/$SUBNET dev eth0 
	if [ $? != 0 ]; then
		error_exit "Adding secondary IP failed for $IPADDR. Exiting.."
	fi


}


if  [ $TYPE == "domain" ]; then


	AGENT="/opt/novell/groupwise/agents/bin/gwmta"
	ps -aef | grep gwmta | grep -v grep > /dev/null
	if [ $? == 0 ]; then

		MTAIP=`ps -aef | grep gwmta | grep -v grep | awk ' { print ($12) } '`
	
		if [ $? == 0 ]; then
			if [ $MTAIP == $IPADDR ]; then
			error_exit "MTA is already running on this server with IP Address: $IPADDR... Exiting"
			fi
		fi
	fi

elif [ $TYPE == "po" ]; then
	AGENT="/opt/novell/groupwise/agents/bin/gwpoa"
	ps -aef | grep gwpoa | grep -v grep
    if [ $? == 0 ]; then
        error_exit "POA is already running on this server... Exiting"
    fi

else
	error_exit "Cant determine agent type, Exiting.."
fi


if [ ! -f $AGENT ]; then 
	echo "$AGENT does not exist.  Install GW agents"; exit 1
fi

if [ ! -d $GWPATH ]; then
	echo "$GWPATH does not exist, exiting"; exit 1
fi

SUBNET=`ip addr show eth0 | grep inet | awk 'NR == 1{ print substr($2, length($2)-1)}'`;
#echo $SUBNET

ping -c 3 $IPADDR > /dev/null
if [ $? == 0 ];then
	ip address show | grep $IPADDR > /dev/null
	if [ $? != 0 ]; then
		error_exit "Ping successful and is not a local address,  can not add secondary IP"
	else
	    IPTYPE="local"
	fi

else
	add_secondary_ip
fi

load_gw
